package sicau.car.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import sicau.car.entity.Admin;
import sicau.car.entity.Application;
import sicau.car.entity.Notice;
import sicau.car.result.R;
import sicau.car.service.AdminService;
import sicau.car.service.ApplicationService;
import sicau.car.service.NoticeService;
import sicau.car.service.UserService;
import sicau.car.utill.BlueCardUtil;
import sicau.car.utill.TokenUtil;


import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ITcz
 * @since 2020-07-28
 */
@RestController
@RequestMapping("/adminCar")
@CrossOrigin
public class AdminController {
    @Autowired
    AdminService adminService;

    @Autowired
    NoticeService noticeService;

    @Autowired
    UserService userService;

    @Autowired
    ApplicationService applicationService;

    //每月第一天自动更新预约车次数
    @Scheduled(cron = "0 0 0 1 * ?")
    private void refreshTimesMonthly(){
        userService.refreshTimesMonthly();
    }

    //每天凌晨3点自动清楚所有token信息
    @Scheduled(cron = "0 0 3 * * ?")
    private void cleanTokenDaily(){
        TokenUtil.deleteAll();
    }

     @PostMapping("/loginIn")
    @ApiOperation("管理员登录")
    public R login(@ApiParam("账号") @RequestParam("account") String account,
                   @ApiParam("密码") @RequestParam("password") String password){
        if(account == null || password == null) {
            return R.error(0,"传入参数非法");
        }
        Admin admin = adminService.login(account, password);
        if(admin != null) {
            //生成一段随机值token，放入token工具类的Hashmap里，并把token传给前端
            String token = TokenUtil.setToken(admin.getCampus());
            HashMap map = new HashMap();
            map.put("token", token);
            //把管理员的校区返回给前端，并在前端存储
            map.put("campus", admin.getCampus());
            return R.ok(map);
        }
        return R.error(0,"账号或密码错误");
    }

    @GetMapping("/loginOut")
    @ApiOperation("管理员登出")
    public R login(HttpServletRequest request){
        String token = request.getHeader("token");
        TokenUtil.removeToken(token);
        return R.ok("退出登录成功");
    }

    @PostMapping("addNotice")
    @ApiOperation("管理员添加公告")
    public R addNotice(@ApiParam("标题") @RequestParam("title") String title,
                       @ApiParam("公告内容") @RequestParam("notice") String content){
        if (title == null || content == null) {
            return R.error("标题或公告内容为空");
        }
        if(noticeService.addNotice(title, content)) {
            return R.ok("添加成功");
        }else {
            return R.error(0,"添加失败");
        }
    }

    @PostMapping("uploadImage")
    @ApiOperation("上传公告里的图片")
    public R setImgUrl(@ApiParam("MultipartFile类型的图片信息(用form data方式上传)") @RequestParam("imgFile") MultipartFile file) throws IOException {
        if(file.isEmpty()) {
            return R.error(501, "参数为空");
        }
        // Get the file and save it somewhere
        byte[] bytes = file.getBytes();
        System.out.println(new String(bytes));
        //存放公告图片的文件夹地址
        String path = "/usr/local/javaImage/";
        File imgFile = new File(path);
        if (!imgFile.exists()) {
            //不存在文件则创建一个目录，路径名由当前File对象指定
            imgFile.mkdirs();
        }
        // 文件名称
        String fileName = file.getOriginalFilename();
        System.out.println(path + fileName);
        //在选定文件中写入图片
        try (FileOutputStream fos = new FileOutputStream(new File(path + fileName))) {
            int len = 0;
            fos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //value 的值为前端渲染图片的绝对路径(图片从/usr/local/javaImage/路径下取)
        String value = "http://113.54.11.32:8080/" + fileName;
        HashMap<String, Object> map = new HashMap<>();
        map.put("url", value);
        return R.ok(map);
    }

    @PostMapping("deleteNotice")
    @ApiOperation("删除公告")
    public R deleteNotice(@ApiParam("公告id") @RequestParam("id") Integer id){
        if(id == null) {
            return R.error(0, "参数为空");
        }
        if(noticeService.deleteNotice(id)){
            return R.ok("删除成功");
        }else {
            return R.error(0,"删除失败");
        }
    }

    @GetMapping("showNotice")
    @ApiOperation("展示公告")
    public R showNotice(@ApiParam("页码") @RequestParam("page") int page,
                        @ApiParam("每页显示公告数") @RequestParam("pageSize") int pageSize){
        if(page > 0 && pageSize > 0){
            Map<String, Object> map = new HashMap<String, Object>();
            IPage<Notice> iPage = noticeService.getAllNotice(page, pageSize);
            map.put("total",iPage.getTotal());
            map.put("result",iPage.getRecords());
            return R.ok(map);
        }else {
            return R.error(0,"参数非法");
        }
    }

    @GetMapping("showPendingOrder")
    @ApiOperation("分页展示短期待处理预约内容")
    public R showPendingOrder(@ApiParam("页码") @RequestParam("page") int page,
                              @ApiParam("每页条数") @RequestParam("pageSize") int pageSize,
                              HttpServletRequest request){
        if(page > 0 && pageSize >0){
            //从header里获取token，通过token获取校区
            String token = request.getHeader("token");
            int campus = TokenUtil.getCampusByToken(token);
            IPage<Application> applicationIPage = applicationService.showPendingOrder(page, pageSize, campus);
            if (applicationIPage != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("total",applicationIPage.getTotal());
                map.put("result",applicationIPage.getRecords());
                return R.ok(map);
            }
        }else {
            return R.error(0,"传入参数非法");
        }
        return R.error(501, "查询失败");
    }

    @GetMapping("showOrderHistory")
    @ApiOperation("分页展示预约历史记录")
    public R showOederHistory(@ApiParam("页码") @RequestParam("page") int page,
                              @ApiParam("每页条数") @RequestParam("pageSize") int pageSize,
                              HttpServletRequest request) {
        if(page > 0 && pageSize > 0) {
            //从header里获取token，通过token获取校区
            String token = request.getHeader("token");
            int campus = TokenUtil.getCampusByToken(token);

            IPage<Application> applicationIPage = applicationService.showOrderHistory(page, pageSize, campus);
            if (null != applicationIPage) {
                Map<String, Object> map = new HashMap<>();
                map.put("total", applicationIPage.getTotal());
                map.put("result", applicationIPage.getRecords());
                return R.ok(map);
            }
        }else {
            return R.error(0, "传入参数非法");
        }
        return R.error(502,"查询失败");
    }

    @GetMapping("queryByLicensePlate")
    @ApiOperation("根据车牌号查询预约结果")
    public R queryByLicensePlate(@ApiParam("车牌号") @RequestParam("licensePlate") String licensePlate,
                                 HttpServletRequest request) {
        if(licensePlate.isEmpty()) {
            return R.error(0, "传入参数为空");
        }
        //从header里获取token，通过token获取校区
        String token = request.getHeader("token");
        int campus = TokenUtil.getCampusByToken(token);
        Application application = applicationService.selectByLicensePlate(licensePlate, campus);
        if(null != application) {
            Map map = new HashMap();
            map.put("result", application);
            return R.ok(map);
        }else {
            return R.ok("结果为空");
        }
    }

    @PostMapping("addOrder")
    @ApiOperation("管理员短期车辆添加")
    public R addOrder(@ApiParam("起始时间") @RequestParam("beginDate") String beginDate,
                      @ApiParam("终止时间") @RequestParam("endDate") String endDate,
                      @ApiParam("name") @RequestParam("name") String name,
                      @ApiParam("预约手机号") @RequestParam("phone") String phone,
                      @ApiParam("车牌号") @RequestParam("plateId") String plateId,
                      HttpServletRequest request){
        //将String类型转化为LocalDateTime对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime beginDate1 = LocalDateTime.parse(beginDate, formatter);
        LocalDateTime endDate1 = LocalDateTime.parse(endDate, formatter);
        if(beginDate == null || endDate == null || name == null || phone == null || plateId == null) {
            return R.error(0, "预约信息为未填写完全");
        }
        //从header里获取token，通过token获取校区
        String token = request.getHeader("token");
        int campus = TokenUtil.getCampusByToken(token);
        Application application = new Application();
        application.setName(name);
        application.setPlateId(plateId);
        application.setBeginDate(beginDate1);
        application.setEndDate(endDate1);
        application.setPhone(phone);
        application.setCampus(campus);
        application.setStatus(1);
        application.setReason("管理员临时车辆添加");
        boolean isSuccess = applicationService.addOrder(application);
        if(isSuccess) {
            return R.ok("添加成功");
        }else {
            return R.error(500, "未知错误添加失败");
        }
    }

    @PostMapping("agreeOrder")
    @ApiOperation("管理员同意预约申请")
    public R agreeOrder(@ApiParam("申请id") @RequestParam("id") Integer id){
        if(id == null){
            return R.error(0, "id为空");
        }
        boolean isSuccess = applicationService.agreeOrder(id);
        if(isSuccess) {
            return R.ok("同意成功");
        }else {
            return R.error(503, "未知错误添加失败");
        }
    }

    @PostMapping("refuseOrder")
    @ApiOperation("管理员拒绝预约申请")
    public R refuseOrder(@ApiParam("申请id") @RequestParam("id") Integer id,
                         @ApiParam("拒绝理由") @RequestParam(name = "reason",required = false) String reason){
        if(null == id){
            return R.error(0, "申请id为空");
        }
        Application application = new Application();
        application.setId(id);
        application.setReason(reason);
        application.setStatus(0);
        boolean isSuccess = applicationService.refuseOrder(application);
        if(isSuccess) {
            return R.ok("拒绝成功");
        }else {
            return R.error(504, "未知错误拒绝失败");
        }
    }

    @GetMapping("getById")
    @ApiOperation("通过id获取单条预约信息")
    public R selectById(@ApiParam("预约信息的id") @RequestParam("id") Integer id){
        if(id == null) {
            return R.error(0, "传入参数为空");
        }
        Application application = applicationService.selectById(id);
        if(null == application){
            return R.error("查询为空");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("result",application);
        return R.ok(map);
    }


    @PostMapping("orderByCode")
    @ApiOperation("二维码申请，所有人都可以申请")
    public R orderByCode(@ApiParam("预约信息") @RequestBody Application application){
        if(null == application){
            return R.error(0, "传入信息为空");
        }
        application.setReason("二维码扫描登记");
        application.setStatus(1);
        int isSuccess = applicationService.order(application);
        if(isSuccess == 0) {
            return R.error(505, "申请失败");
        }else {
            return R.ok("申请成功");
        }
    }

    @GetMapping("queryWhite")
    @ApiOperation("查询蓝卡云预约车记录")
    public R query(@ApiParam("车牌号") @RequestParam("PlateNumb") String plateNumber,
                   HttpServletRequest request) {
        //从header里获取token，通过token获取校区
        String token = request.getHeader("token");
        int campus = TokenUtil.getCampusByToken(token);

        String res ="";
        if (campus == 0) {
            res = BlueCardUtil.querychengdu(plateNumber);
        }else if (campus == 1){
            res = BlueCardUtil.queryYaAn(plateNumber);
        }

        return R.ok(res);
    }

    @GetMapping("deleteWhite")
    @ApiOperation("删除蓝卡云预约车记录")
    public R deleteWhite(@ApiParam("车牌号") @RequestParam("PlateNumb") String plateNumber,
                   HttpServletRequest request) {
        //从header里获取token，通过token获取校区
        String token = request.getHeader("token");
        int campus = TokenUtil.getCampusByToken(token);

        if (campus == 0) {
            BlueCardUtil.deletechengdu(plateNumber);
        }else if (campus == 1){
            BlueCardUtil.deleteYaAn(plateNumber);
        }

        return R.ok();
    }

}

